package cn.itcast.controller.system;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.system.Dept;
import cn.itcast.service.system.DeptService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/system/dept")
public class DeptController extends BaseController {
    @Autowired
    private DeptService deptService;

    @RequestMapping(value = "/list",name ="查询所有部门数据")
    public String findAll(@RequestParam(defaultValue = "1",name = "page") int pageNum,@RequestParam(defaultValue = "10") int pageSize){
//        当前登录人所属部门的id
        PageInfo<Dept> pageBean = deptService.findPage(getCompanyId(),pageNum,pageSize);
        request.setAttribute("page",pageBean);
        return "system/dept/dept-list";
    }
    @RequestMapping(value = "/toAdd",name ="进入到添加部门的页面")
    @RequiresPermissions("新增部门")
    public String toAdd(){
//        查询当前登录人所在企业的所有部门数据
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);
        return "system/dept/dept-add";
    }

    @RequestMapping(value = "/edit",name ="保存部门数据") //新增或修改时都会进入这个方法
    public String edit(Dept dept){
        if(dept.getParent().getId().equals("")){
            dept.getParent().setId(null);
        }

        if(StringUtils.isEmpty(dept.getId())){
            //id为空新增 save
            dept.setId(UUID.randomUUID().toString());
            dept.setCompanyId(getCompanyId());
            dept.setCompanyName(getCompanyName());
            deptService.save(dept);
        }else{
            deptService.update(dept); //id如果有值 update
        }
//        不管新增还是修改都是要重定向到列表页面
        return "redirect:/system/dept/list.do";  //redirect 重定向  在浏览器发起的请求
    }
    @RequiresPermissions("修改部门")
    @RequestMapping(value = "/toUpdate",name ="进入到编辑页面")
    public String toUpdate(String id){
        Dept dept = deptService.findById(id);
        request.setAttribute("dept",dept);

        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);
        return "system/dept/dept-add";
    }
    @RequiresPermissions("删除部门")
    @RequestMapping(value = "/delete",name ="根据id删除部门数据")
    public String delete(String id){
        deptService.delete(id);

        return "redirect:/system/dept/list.do";
    }




}
